#include "dir.h"

int handle_mkdir(session_t *session, int netfd, MYSQL *mysql, const char*destDir){
    char buf[1024] = {0};

    int parentID = -1;
    char lastToken[MAX_PATH_LEN] = {0}; //即传进来是路径+名的话 切割后得到的名
    int ret = cut_path(session,mysql,destDir,&parentID,lastToken,buf,sizeof(buf));
    if(ret != 0){
        sendtlv(netfd, buf);
        return -1;
    }
    //拿到了父目录ID -> 查找是否有重名目录
    char query[MAX_QUERY_LEN] = {0};
    sprintf(query,
            "select id from file where username = '%s' and "
            "parent_id = %d and filename = '%s' and tomb = 0",
            session->username, parentID, lastToken);
    ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);

    MYSQL_RES *table = mysql_store_result(mysql);
    MYSQL_STORE_RESULT_CHECK(table, mysql);

    if(mysql_num_rows(table) > 0){
        mysql_free_result(table);
        strncpy(buf, "目录已存在.", sizeof(buf)-1);
        sendtlv(netfd, buf);
        return -1;
    }
    mysql_free_result(table);
    
    //无同名目录 -> 目录名插入文件表 并不mkdir真实创建
    //拼接出需插入的path
    bzero(query, sizeof(query));
    sprintf(query,
            "select path from file where id = %d and username = '%s' and "
            "filetype = 'd' and tomb = 0",
            parentID,session->username);
    ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);

    table = mysql_store_result(mysql);
    MYSQL_STORE_RESULT_CHECK(table, mysql);
    
    MYSQL_ROW row = mysql_fetch_row(table);
    
    char parentPath[MAX_PATH_LEN] = {0};
    bzero(parentPath, sizeof(parentPath));
    strncpy(parentPath, row[0], sizeof(parentPath)-1);
    mysql_free_result(table);
    //拼接有两种情况 父目录path 为 / 或 /xxx
    char insertPath[MAX_PATH_LEN] = {0};
    if(strcmp(parentPath,"/")==0){
        sprintf(insertPath, "/%s", lastToken);
    }else{
        sprintf(insertPath, "%s/%s", parentPath, lastToken);
    }
    
    //插入
    bzero(query, sizeof(query));
    sprintf(query,
            "insert into file (username,parent_id,filename,filetype,path,tomb)"
            "values('%s',%d,'%s','d','%s',0)",
            session->username,parentID,lastToken,insertPath);
    ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);
    
    strncpy(buf, "目录创建成功.", sizeof(buf)-1);
    sendtlv(netfd, buf);
    return 0;
}
